<template>
<!-- 账号列表 -->
  <div>
    <div class="maxBox">
      <!-- 标题组件 -->
      <panel title="账号列表">
        <!-- 内容区域 -->
        <div class="content">
          <el-table
            ref="multipleTable"
            :data="tableData"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column prop="account" label="账号"></el-table-column>
            <el-table-column prop="userGroup" label="用户组"> </el-table-column>

            <el-table-column label="创建时间">
              <template slot-scope="scope">
                {{ scope.row.ctime | filterTime }}  <!-- 转时间格式 -->
              </template>
            </el-table-column>

            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="editBtn(scope.row)" size="small">编辑</el-button>
                <el-button
                  type="danger "
                  size="small"
                  @click="delAccount(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页器 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-sizes="[5, 10, 15, 20, 30]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>

          <!-- 批量删除按钮 -->
          <div class="btnn">
            <el-button type="danger" @click="delAll()">批量删除</el-button>
            <el-button @click="toggleSelection()" type="primary"
              >取消选择</el-button
            >
          </div>
        </div>
      </panel>

        <!-- 点击编辑的弹窗 -->
      <el-dialog title="编辑账号" :visible.sync="isShow">

        <el-form :model="formData">
          <el-form-item label="账号" label-width="110px">
            <el-input v-model="formData.account" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户组" label-width="110px">
            <el-select v-model="formData.userGroup" placeholder="请选择用户组">
              <el-option label="超级管理员" value="超级管理员"></el-option>
              <el-option label="普通管理员" value="普通管理员"></el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="isShow = false">取 消</el-button>
          <el-button type="primary" @click="editAccount()">确 定</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>
// 导入公共标题组件
import Panel from "../../components/Panel.vue";
import { userList, userDel, delUserAll ,userEdit } from "@/api/user.js";    

export default {
  data() {
    return {
      // 当前页码
      page: 1,
      pageSize: 5,
      total: 10,

      tableData: [],
      // 被选中项
      multipleSelection: [],

      // 是否显示弹窗 默认不显示
      isShow:false,
      // form表单数据
      	formData:{
					id:'',
					account:'',
					userGroup:''
				},

    };
  },
  // 注册组件
  components: {
    Panel,
  },

  methods: {
      // 修改账号信息 确定按钮
			async editAccount(){
				let res = await userEdit(this.formData)
				if(res.data.code ===0){  //如果修改成功
					this.isShow = false   //就关闭弹窗
					this.getUserList();   //重新调用 渲染页面
        //成功之后 中央事件总线 跨组件更新用户名
          this.$bus.$emit('changeUser');
				}
			},

      //点击编辑按钮
			editBtn(row){
				// console.log(row);
				let {id,account,userGroup} = row;
				this.formData ={id,account,userGroup}
				this.isShow = true;        

			},

    
    // 批量取消选择
     toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }},
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },


    // 单删用户按钮
    delAccount(id) {
      this.$confirm("是否确认删除该账号", "提示", {
        // if()
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",

      }).then(async () => {
          let res = await userDel({ id });
          if (res.data.code === 0) {
            //成功删除后 重新请求列表
            this.getUserList();
            console.log("被删用户ID：" + res.config.params.id);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 批量删除用户
    delAll() {
      let delArr = [];
      this.multipleSelection.forEach((item) => {
        console.log( "被删除的用户："+item.id);    // 拿到选中项
        delArr.push(item.id);
      });
      delArr = JSON.stringify(delArr);
      // console.log(delArr);      //转换为json字符串
      // 接口
      delUserAll({ ids: delArr }).then((res) => {
        // 重新调用函数 渲染页面
        if (res.data.code === 0) {
          this.getUserList();
          // console.log(res.data);
        }
      });
    },

    // 切换每页条数
    handleSizeChange(data) {
      this.pageSize = data;
      this.getUserList(); //调用重新渲染数据
    },
    // 切换当前页码
    handleCurrentChange(page) {
      this.page = page;
      this.getUserList(); //调用重新渲染数据
    },

    // 请求用户列表
    async getUserList() {
      let data = {
        currentPage: this.page,
        pageSize: this.pageSize,
      };
      // 请求接口
      let res = await userList(data);
      let { total } = res.data;
      this.total = total;
      this.tableData = res.data.data;
    },
  },

  // 进入页面请求数据
  created() {
    // 请求用户列表
    this.getUserList();
  },
  
  filters: {
    // 时间函数
    filterTime(timeStr) {
      let date = new Date(timeStr);
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      let d = date.getDate();
      let h = date.getHours();
      let mini = date.getMinutes();
      let s = date.getSeconds();
      m = m < 10 ? "0" + m : m;
      d = d < 10 ? "0" + d : d;
      h = h < 10 ? "0" + h : h;
      mini = mini < 10 ? "0" + mini : mini;
      s = s < 10 ? "0" + s : s;
      return `${y}-${m}-${d} ${h}:${mini}:${s}`;
    },
  },
};
</script>

<style lang="less" scoped>
.maxBox {
  width: 100%;
  height: 100%;
}
.btnn {
  margin-top: 18px;
}
.el-select{
  width: 100%;
}
</style>